package models

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/astaxie/beego/orm"
	"fmt"
	"strconv"
)



//由于model这个名字叫 UserInfo 那么操作的表其实 user_info
type UserInfo struct {
	Id int64
	Uid      string
	Username string
	Password string
	Usertype string
	Regtime  string
	Timestamp string
	Company string
	Department string
	Add string
	Delete string
	Change string
	Querycap string
}


//根据用户名查询用户所在公司
func QueryCompanyByUsername(username string)string {
	o := orm.NewOrm()
	var userrows []UserInfo
	if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ", username).QueryRows(&userrows); err != nil {
		fmt.Println("err")
	}
	company := ""
	for _, userrow := range userrows {
		company = userrow.Company
	}
	return company
}




//添加用户
func AddUser(user_info *UserInfo)(int64,error){
    db := orm.NewOrm()
	id,err := db.Insert(user_info)
	return id,err
}



//查询所有用户
func Showalluser(userDataChan chan string,username string,page string,size string) int {
	//fmt.Println("=====超级用户查询用户列表=======")
	var totalItem int = 0
	o := orm.NewOrm()
	var userrows []UserInfo
	if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ",username).QueryRows(&userrows); err != nil {
		fmt.Println("err")
	}

	userflag := false
	company := ""
	//检查该用户是否是超级用户
	for _,userrow := range userrows{
		if userrow.Usertype == "superuser" {
			userflag = true
			company = userrow.Company
			break
		}
	}
	if userflag == true{
		var userrows []UserInfo
		pageint, _ := strconv.ParseInt(page, 10, 64)
		sizeint, _ := strconv.ParseInt(size, 10, 64)
		o.Raw("SELECT COUNT(*) FROM user_info where company = ? ", company).QueryRow(&totalItem)
		if _, err := o.Raw("SELECT * FROM user_info where company = ?  limit ?,?", company, (pageint-1)*sizeint, sizeint).QueryRows(&userrows); err != nil {
			fmt.Println("err")
			return 0
		}
		var  i int64= (pageint-1)*sizeint;
		for _,userrow := range userrows{
			i++
			id := strconv.FormatInt(i,10)
			userInfos :=id+ "and"+ userrow.Uid+
				 "and"+ userrow.Username+
				 "and"+userrow.Usertype+
				//"and"+fencerow.Fencepoint+
				"and"+userrow.Company+
				"and"+userrow.Department
			userDataChan <- userInfos
		}
	}
	return totalItem
}

//删除用户接口
func Deleteuser(superuser string,username string)  string{
	o := orm.NewOrm()
	var userrows []UserInfo
	if _, err := o.Raw("SELECT * FROM user_info WHERE username = ?  ",superuser ).QueryRows(&userrows); err != nil {
		fmt.Println("err")
	}
	userflag := false
	//检查该用户是否是超级用户
	for _,userrow := range userrows{
		if userrow.Usertype == "superuser" {
			userflag = true
			break
		}
	}
	result := ""
	if userflag == true{
		var userrows []UserInfo
		if _, err := o.Raw("DELETE  FROM user_info WHERE username = ?  ",username).QueryRows(&userrows); err != nil {
			fmt.Println("err")
		}
		result = "success"
	}else {
		result = "failed"
	}
	return result
}






